package com.huibao.hulibao.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.huibao.hulibao.R;
import com.huibao.hulibao.constant.GlobalConstants;
import com.huibao.hulibao.entity.LoginEntity;
import com.huibao.hulibao.entity.ResultEntity;
import com.huibao.hulibao.entity.ServerEntity;
import com.huibao.hulibao.utils.DialogUtils;
import com.huibao.hulibao.utils.MyUtils;
import com.huibao.hulibao.utils.PreUtils;
import com.huibao.hulibao.utils.T;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by lizhaoyong on 2018/5/14.
 */
public class ServerFinishActivity extends BaseActivity {

    @BindView(R.id.iv_back)
    ImageView iv_back;
    @BindView(R.id.tv_back)
    TextView tv_back;
    @BindView(R.id.tv_server_detail_title)
    TextView tv_server_detail_title;
    @BindView(R.id.tv_server_finish)
    TextView tv_server_finish;
    @BindView(R.id.et_finish)
    EditText et_finish;


    private LoginEntity le;
    // 网络请求加载对话框
    private Dialog myDialog;

    private String stime;
    private String TaskId;

    private String zhixinzhong = "";
    public ServerEntity.ServerDetailData sdd;


    @OnClick({R.id.iv_back, R.id.tv_back})
    public void back() {
        onBackPressed();
    }

    // 确认结束任务
    @OnClick(R.id.tv_server_finish)
    public void finishOrder() {
        AlertDialog dialog = new AlertDialog.Builder(ServerFinishActivity.this).setTitle(R.string.shifouquerenjieshurenwu)
                .setPositiveButton(getResources().getString(R.string.confirm), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 是否需要进行结束扫码校验
                        if (sdd.ServeEndScanLabel.equals("")) {
                            finishRenwuToServer();
                        } else {
                            Intent intent = new Intent(getApplicationContext(), ScanListActivity.class);
                            intent.putExtra("ServerDetailData", sdd);
                            intent.putExtra("finish", "finish");
                            intent.putExtra("content", et_finish.getText().toString());
                            startActivity(intent);
                        }

                    }
                }).setNegativeButton(getResources().getString(R.string.quxiao), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).show();
        dialog.setCanceledOnTouchOutside(false);
    }

    public void showDialog() {
        myDialog = DialogUtils.createLoadingDialog(ServerFinishActivity.this, getResources().getString(R.string.jiazaizhong));
    }

    public void closeDialog() {
        DialogUtils.closeDialog(myDialog);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_server_finish);
        ButterKnife.bind(this);
        le = (LoginEntity) PreUtils.getObject(getApplicationContext(), "LoginEntity");
        String title = getIntent().getStringExtra("title");
        stime = getIntent().getStringExtra("stime");
        TaskId = getIntent().getStringExtra("TaskId");
        zhixinzhong = getIntent().getStringExtra("zhixinzhong");
        sdd = (ServerEntity.ServerDetailData) getIntent().getSerializableExtra("ServerDetailData");
        tv_server_detail_title.setText(title);
        // LogUtils.d("endScanLabel = " + sdd.ServeEndScanLabel);
        LogUtils.d("status = " + PreUtils.getParam(getApplicationContext(), "RenWuStatus", ""));


    }


    @Override
    public void onBackPressed() {
        if (zhixinzhong == null || zhixinzhong.equals("")) {
            finish();
        } else {
            Intent intent = new Intent(getApplicationContext(), MainActivity.class);
            startActivity(intent);
            finish();
        }
        super.onBackPressed();
    }

    // 结束任务请求
    public void finishRenwuToServer() {

        String etime = MyUtils.getFormatTimeToString(System.currentTimeMillis()).replace(":", "%3A");
        if (le == null) {
            return;
        }
        RequestParams params = new RequestParams(GlobalConstants.URL);
        params.setCacheMaxAge(0);
        showDialog();
        JSONObject object = new JSONObject();
        try {
            object.put("taskid", TaskId);

            object.put("stime", stime.replace(":", "%3A"));
            object.put("etime", etime);
            object.put("clue", et_finish.getText().toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        params.addBodyParameter("q", le.Message.Session + GlobalConstants.URL_RENWU_FINISH + object.toString());
        LogUtils.d("params = " + params.toString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                closeDialog();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(result);
                    LogUtils.d("result = " + jsonObject.toString());
                    ResultEntity re = GlobalConstants.gson.fromJson(jsonObject.toString(), ResultEntity.class);
                    if (re != null && re.State.equals(GlobalConstants.SUCCESS_CODE)) {
                        T.show(getApplicationContext(), getString(R.string.renwujieshuchenggong), 0);
                        Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                        intent.putExtra("jumpWeb", true);
                        String jumpUrl = GlobalConstants.HOST + "AppWap/PDA_APP/WebTools/ShowServeDetail.aspx?ss=" + le.Message.Session + "&sid=" + sdd.ServeId;
                        intent.putExtra("jumpUrl", jumpUrl);
                        startActivity(intent);
                        finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                closeDialog();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                closeDialog();
            }

            @Override
            public void onFinished() {
                closeDialog();
            }
        });
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (MyUtils.isShouldHideInput(v, ev)) {
                if (MyUtils.hideInputMethod(this, v)) {
                    return true; //隐藏键盘时，其他控件不响应点击事件==》注释则不拦截点击事件
                }
            }
        }
        return super.dispatchTouchEvent(ev);
    }
}
